import { login } from '@/api/user'
// 引入花裤衩封装好的js-cookie
import { setToken, getToken, removeToken } from '@/utils/auth'
import { getProfile, getUserDetialByid } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  // 持久化步骤二，每当刷新，初始化尝试获取旧数据
  // token: localStorage.getItem('token') || ''
  // 这里使用cookie
  token: getToken() || '',
  profile: null
}
const mutations = {
  // 修改state中token的数据
  setToken(state, data) {
    // 持久化步骤一，每当数据发生改变，备份一份到本地
    // localStorage.setItem('token', data)
    // 这里使用cookie
    setToken(data)
    state.token = data
  },
  setProfile(state, data) {
    state.profile = data
  },
  // 点击退出时，清空token，profile
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeProfile(state) {
    state.profile = null
  }
}
const actions = {
  // 修改token的值
  async login(store, data) {
    const res = await login(data)
    localStorage.setItem('loginTime', Date.now())
    // console.log('vuex获取数据', res)
    store.commit('setToken', res)
  },
  async getProfile(store) {
    const res = await getProfile()
    const detial = await getUserDetialByid(res.userId)
    // console.log(34, res)
    store.commit('setProfile', { ...res, ...detial })
  },
  // 退出登录清空
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
